const util = require('../util/util.js')
const routeConfig = require('../config/routeConfig')
const Navigation = require('../models/navigation.model.js')
const responseResultData = util.responseResultData
const filterVerify = (req, res, next) => {
  if (routeConfig.whitePath.includes(req.url)) {
    next()
    return
  }
  const urlList = req.url.split('/')
  if (urlList.length !== 4) {
    responseResultData(res, 200, false, '请求地址格式错误', '')
    return
  }
  Navigation.getNavigationByController(urlList[2], urlList[3], (err, data) => {
    if (err) {
      responseResultData(res, 200, false, err.message || '获取权限信息错误', '')
      return
    }
    if (data.length === 0) {
      responseResultData(res, 200, false, '权限信息错误', '')
      return
    }
    const navigationId = data[0].id
    const permission = req.auth.permission.split(',').map(item => parseInt(item))
    if (!permission.includes(navigationId)) {
      responseResultData(res, 200, false, '未授权该权限', '')
      return
    }
    next()
  })
}
module.exports = filterVerify